package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.entity.ApUserSearch;
import com.heima.search.entity.dto.HistorySearchDto;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.util.AppUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public void saveUserSearch(String keyword,Long userId) {
        log.info("线程池异步调度开始执行-----线程名称:{}", Thread.currentThread().getName());
        if (StringUtils.isEmpty(keyword)) {
            return;
        }
        //1. 判断搜索历史记录是否存在
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        if (apUserSearch != null) {
            //1.1 存在 更新保存时间
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }
        //1.2 不存在 , 将搜索历史记录插入数据库
        //判断用户搜索历史记录数量是否超过10条
        query = Query.query(Criteria.where("userId").is(userId)).with(Sort.by("createdTime").descending());
        List<ApUserSearch> userSearchList = mongoTemplate.find(query, ApUserSearch.class);

        //1.2.1 超过 , 替换最后一条
        if (userSearchList.size() >= 10) {
            ApUserSearch last_ApUserSearch = userSearchList.get(userSearchList.size() - 1);
            last_ApUserSearch.setKeyword(keyword);
            last_ApUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(last_ApUserSearch);
            return;
        }

        //1.2.2 不超过, 直接保存到数据库
        apUserSearch = new ApUserSearch();
        apUserSearch.setCreatedTime(new Date());
        apUserSearch.setKeyword(keyword);
        apUserSearch.setUserId(userId.intValue());
        apUserSearch.setId(ObjectId.get().toHexString());
        mongoTemplate.save(apUserSearch);
    }

    @Override
    public ResponseResult load() {
        Query query = Query.query(Criteria.where("userId").is(AppUserThreadLocalUtil.get().getId())).with(Sort.by("createdTime").descending());
        List<ApUserSearch> userSearchList = mongoTemplate.find(query, ApUserSearch.class);

        return ResponseResult.okResult(userSearchList);
    }

    @Override
    public ResponseResult delete(HistorySearchDto dto) {
        if (dto == null || StringUtils.isEmpty(dto.getId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Query query = Query.query(Criteria.where("id").is(dto.getId()).and("userId").is(AppUserThreadLocalUtil.get().getId()));
        mongoTemplate.remove(query, ApUserSearch.class);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
